#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time      :2022/5/19 14:22
# @Author    :cjw
from selenium.webdriver import Remote, DesiredCapabilities
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager

from web_wework.setting import *
from web_wework.browser.base_browser import BaseBrowser


class Chrome(BaseBrowser):
    """谷歌浏览器启动类"""
    start_maximized = CHROME_START_MAXIMIZED  # 浏览器最大化
    method_mark = CHROME_METHOD_MARK  # 控制浏览器启动特性是否设置
    option_mark = CHROME_OPTION_MARK  # 控制浏览器启动参数是否添加
    is_debugger = IS_DEBUGGER  # 控制是否开启复用浏览器
    experimental_option = CHROME_EXPERIMENTAL_OPTION  # 实验选项

    # 是否通过webdriver-manager管理驱动
    is_webdriver_manager = IS_WEBDRIVER_MANAGER

    @property
    def options(self):
        """谷歌浏览器特有启动参数"""
        if self.option_mark:
            options = self._option()
            # 复用浏览器不能设置额外的启动参数
            if self.is_debugger:
                options.debugger_address = DEBUGGER_ADDRESS
            else:
                # 添加启动参数和实验参数
                options.add_argument(self.start_maximized)
                for k, v in self.experimental_option.items():
                    options.add_experimental_option(k, v)
                options.headless = HEADLESS
            return options
        return

    @property
    def browser(self):
        """启动谷歌浏览器，返回浏览器实例"""
        # 判断是否通过webdriver-manager管理驱动
        if self.is_webdriver_manager:
            service = Service(ChromeDriverManager().install())
        else:
            service = Service(executable_path=self.chrome_driver_path)

        # 判断是否远程启动
        if self._browser == Remote:
            # 判断是否添加启动控制参数
            if options := self.options:
                chrome = self._browser(self._command_executor, options=options,
                                       desired_capabilities=DesiredCapabilities.CHROME)
            else:
                chrome = self._browser(self._command_executor,
                                       desired_capabilities=DesiredCapabilities.CHROME)
        else:
            if options := self.options:
                chrome = self._browser(service=service, options=options)
            else:
                chrome = self._browser(service=service)
        return chrome
